package com.fz.study.project.config;

import com.fz.study.project.interceptor.LoginCheckInterceptor;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@RequiredArgsConstructor
@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    private final LoginCheckInterceptor loginCheckInterceptor;
    //    配置消息转换器
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        var converterList = converters.stream()
                .filter(converter -> !(converter instanceof StringHttpMessageConverter))
                .toList();
        converters.clear();
        converters.addAll(converterList);
    }

    //    设置拦截器
    @Bean
    public CorsFilter corsFilter() {
        var corsConfiguration = new CorsConfiguration();
        // 添加允许来源
        corsConfiguration.addAllowedOrigin("*");
        // 添加允许标头
        corsConfiguration.addAllowedHeader("*");
        // 添加允许方法
        corsConfiguration.addAllowedMethod("*");
        var source = new UrlBasedCorsConfigurationSource();
        // 配置监听路径  "/**"表示监听所有请求信息
        source.registerCorsConfiguration("/**", corsConfiguration);
        return new CorsFilter(source);
    }

//    配置拦截器路径
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**");
//    }
}
